home *** CD-ROM | disk | FTP | other *** search
- Path: nntp208.reach.com!usenet
- From: Cliff Vick <cvick@reach.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Visibility Restricted to Compiler
- Date: Tue, 06 Feb 1996 11:34:01 -0500
- Organization: Reach Networks
- Message-ID: <311782F9.17C3@reach.com>
- References: <4eq8td$hpu@vixen.cso.uiuc.edu> <4ettcg$d1f@mastermind.odi.com>
- NNTP-Posting-Host: jmkpc.reach.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b5 (Win95; I)
-
- >If the constructor is private, it can only be called by the class
- >itself. It can't even be called implicitly by new.
-
- Not true. You can call the constructor by using new (as in the
- following):
-
- A good reason to want a private constructor is when you want to control
- how many instantations of an object there are at run time. For example,
- say I want an object that is only instantiated once and once only, but
- also providing access to this single object to everyone. I could create
- something like the following:
-
- Declaration:
-
- class SingleObject
- {
- public:
- static SingleObject* Instance();
- private:
- SingleObject();
-
- static SingleObject * instance;
- };
-
-
- Implementation:
-
- SingleObject* SingleObject::instance = NULL;
-
- SingleObject* SingleObject::Instance()
- {
- if (instance == NULL)
- instance = new SingleObject;
- return instance;
- }
-
-
- The above is a simple view of achieving only one instance of a specific
- class. In practice, you might want to implement some kind of reference
- counting mechanism so that you know how many 'things' are using this
- instance, then when you are ready to get rid of the single object, you
- can safely destruct only when no one is using it.
-
- cliffv@reach.com
-